<template>
  <div class="app-container full-height">
    <el-row>
      <el-col :span="12">
        <div class="content full-height mr12" style="position: relative">
          <l-map
            :center="center"
            :options="options"
            :zoom="zoom"
            @update:center="centerUpdate"
            @update:zoom="zoomUpdate"
          >
            <l-tile-layer
              v-for="(item, index) in urls"
              :key="index"
              :url="item"
            />
            <l-circle
              v-for="(circle, index) in circles"
              :key="`circle${index}`"
              :color="circle.color"
              :fill-color="circle.color"
              :lat-lng="circle.center"
              :opacity="0"
              :radius="circle.radius"
            />

            <l-marker
              v-for="(item, index) in sqzs"
              :key="`device${index}`"
              :icon="getIcon(item)"
              :lat-lng="[item.lat, item.lng]"
              :title="item.name"
              @click="showDevice(item)"
            >
              <l-tooltip :options="markerOptions">
                <div class="d-flex align-items-center">
                  <span>{{ item.name }}</span>
                  <span
                    class="dot ml4"
                    :class="`bg-${item.type}`"
                    style="display: inline-block"
                  ></span>
                </div>
              </l-tooltip>
            </l-marker>
          </l-map>
          <div
            style="
              position: absolute;
              top: 24px;
              right: 24px;
              z-index: 9999;
              color: #fff;
            "
          >
            当前选中：{{ device.name || '' }}
          </div>
        </div>
      </el-col>
      <el-col :span="12">
        <div v-loading="loading">
          <div class="tip">
            <el-date-picker
              v-model="params.created_at"
              align="center"
              end-placeholder="结束日期"
              range-separator="~"
              start-placeholder="开始日期"
              type="daterange"
              value-format="yyyy-MM-dd"
            />
            <el-button
              class="ml12"
              icon="el-icon-search"
              type="primary"
              @click="handleSearch"
            >
              查询
            </el-button>
            <el-button
              class="ml12"
              icon="el-icon-download"
              type="success"
              @click="handleExport"
            >
              导出
            </el-button>
            <el-button
              class="ml12"
              icon="el-icon-plus"
              type="danger"
              @click="handleAddCell"
            >
              导入
            </el-button>
          </div>
          <div class="h12"></div>
          <el-tabs v-model="activeName" type="card">
            <el-tab-pane label="趋势" name="first">
              <ve-line
                v-if="results.length > 0"
                :data="chartData"
                :extend="chartExtend"
                :height="chartHeight"
                :settings="chartSettings"
              />
              <el-empty v-else description="暂无任何记录" />
            </el-tab-pane>
            <el-tab-pane label="列表数据" name="second">
              <el-table border :data="results" :height="height" stripe>
                <el-table-column
                  align="center"
                  label="编号"
                  type="index"
                  width="80"
                />
                <el-table-column align="center" label="日期" prop="日期" />
                <el-table-column
                  align="center"
                  label="湿度(%)"
                  prop="湿度(%)"
                />
                <el-table-column
                  align="center"
                  label="温度(℃)"
                  prop="温度(℃)"
                />
                <el-table-column
                  align="center"
                  label="电压(V)"
                  prop="电压(V)"
                />
                <el-table-column
                  align="center"
                  fixed="right"
                  label="操作"
                  width="100"
                >
                  <template #default="{ row }">
                    <el-link
                      class="mr12"
                      icon="el-icon-edit"
                      type="primary"
                      @click="handleEdit(row)"
                    >
                      修改
                    </el-link>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
          <edit ref="edit" />
        </div>
      </el-col>
    </el-row>
    <el-dialog title="载入数据文件" :visible.sync="dialogVisible" width="800px">
      <el-empty v-if="exportData.length === 0" description="暂无任何计算结果">
        <file-upload :action="uploadUrl" :name="name" @onSuccess="onSuccess" />
      </el-empty>
    </el-dialog>
  </div>
</template>

<script>
  import { dclassCodeMap, map } from '@/utils/constant'
  import Edit from './components/Edit'
  import FileUpload from '@/components/FileUpload'
  import { mapGetters } from 'vuex'
  import { statistics } from '@/api/device'
  import { getCurrentDate, getNextDate, removeEmptyField } from '@/utils'
  import { getDeviceImage, getDeviceStatus } from '@/utils/device'
  import * as XLSX from 'xlsx'
  export default {
    components: {
      Edit,
      FileUpload,
    },
    data() {
      const currentDate = getCurrentDate()
      return {
        params: {
          per: '1h',
          created_at: [currentDate, getNextDate(currentDate, 1)],
        },
        activeName: 'first',
        zoom: 18,
        center: map.center,
        options: map.options,
        urls: map.mapTypes[map.initType],
        markerOptions: {
          permanent: true,
          interactive: false,
          direction: 'bottom',
          offset: [0, 8],
          className: 'anim-tooltip',
        },
        daterange: '',
        dialogVisible: false,
        exportData: [],
        uploadUrl: 'https://api.zesi.com.cn/idata/util/upload',
        name: 'awc',
        device: {},
        loading: false,
        circles: [
          {
            serialno: '0110.0007.2027000724',
            name: '大曹庄农场喷灌机-0724',
            radius: 150,
            center: [37.467294, 114.913504],
            color: `rgba(248, 9, 9, 1)`,
            lat: 37.467294,
            lng: 114.913504,
            latlngs: [
              [37.467294, 114.913504],
              [37.46771532274502, 114.91188941023749],
            ],
          },
        ],
        tableData: [],
        height: 'calc(100vh - 284px)',
        chartSettings: {},
        chartHeight: 'calc(100vh - 234px)',
        chartExtend: {
          series: {
            showSymbol: false,
          },
          grid: {
            left: '2%',
            right: '2%',
            bottom: '6%',
            top: '6%',
            containLabel: true,
          },
        },
        results: [],
        chartData: {},
      }
    },
    computed: {
      ...mapGetters(['devices']),
      sqzs() {
        const res = this.devices
          .filter(
            (item) =>
              +item.product_type === dclassCodeMap.sqz && item.map_show === 1
          )
          .map((val) => {
            val.type = getDeviceStatus(val) === 'd_run' ? 'success' : 'danger'
            return val
          })
        return res
      },
    },
    created() {
      if (this.sqzs.length > 0) {
        this.device = this.sqzs[0]
        this.statistics(this.device.serialno)
      }
    },
    methods: {
      getDeviceStatus(item) {
        return getDeviceStatus(item)
      },
      getDeviceImage(item) {
        return getDeviceImage(item)
      },
      async statistics(serialno) {
        const params = { serialno }
        this.params = { ...this.params, ...params }
        const { data } = await statistics(removeEmptyField(this.params))
        this.chartData = this.formatStatistics(data.categories, data.series)
      },
      formatStatistics(categories, series) {
        const columns = ['日期']
        const rows = []
        for (let i = 0; i < categories.length; i++) {
          const item = { 日期: categories[i] }
          for (const citem of series) {
            item[citem.name] = citem.data[i]
            if (i === 0) {
              columns.push(citem.name)
            }
          }

          rows.push(item)
        }
        this.results = rows
        return {
          columns: columns,
          rows: rows,
        }
      },
      zoomUpdate(zoom) {
        this.zoom = zoom
      },
      centerUpdate(center) {
        this.center = center
      },
      onSuccess(response) {
        const { errorCode, msg, data } = response
        if (errorCode !== 0) {
          this.$message({
            message: (msg && `上传失败，失败原因：${msg}`) || '上传失败',
            type: 'error',
          })
          this.$emit('onError', data)
        } else {
          this.$baseMessage('操作成功', 'success')
          this.exportData = data
        }
      },
      showDevice(row) {
        this.loading = true
        this.statistics(row.serialno)
        this.device = row
        setTimeout(() => {
          this.loading = false
        }, 2000)
      },
      getIcon(item) {
        // eslint-disable-next-line no-undef
        return L.icon({
          iconSize: [28, 28],
          iconUrl: getDeviceImage(item),
        })
      },
      handleSearch() {
        this.statistics(this.device.serialno)
      },
      handleExport() {
        let title = ['日期', '温度(℃)', '湿度(%)', '电压(V)']
        let data = []
        this.results.forEach((item) => {
          let temp = []
          title.forEach((citem) => {
            temp.push(item[citem])
          })
          data.push(temp)
        })
        data.unshift(title)
        // 将数据转换为工作表
        const ws = XLSX.utils.aoa_to_sheet(data)

        // 创建工作簿并添加工作表
        const wb = XLSX.utils.book_new()
        XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')

        // 生成Excel文件并导出
        XLSX.writeFile(wb, 'output.xlsx')
      },
      handleAddCell() {
        this.dialogVisible = true
      },
    },
  }
</script>

<style lang="scss" scoped></style>
